package com.pay.controller;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.pay.config.AlipayConfig;
import com.pay.pojo.OrderInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Controller
public class PayController {
    @Autowired
    private HttpServletResponse response;

    @PostMapping("/alipay")
   public void pay(OrderInfo orderInfo)throws Exception{

       //获得初始化的AlipayClient
       AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

       //设置请求参数
       AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
       alipayRequest.setReturnUrl(AlipayConfig.return_url);
       alipayRequest.setNotifyUrl(AlipayConfig.notify_url);


       alipayRequest.setBizContent("{\"out_trade_no\":\""+ orderInfo.getOid() +"\","
               + "\"total_amount\":\""+ orderInfo.getAmount() +"\","
               + "\"subject\":\""+ orderInfo.getSubject() +"\","
               + "\"body\":\""+ orderInfo.getDesc() +"\","
               + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");



       //请求
       String result = alipayClient.pageExecute(alipayRequest).getBody();
        response.setContentType("text/html;charset=utf-8");
       //输出
        PrintWriter out = response.getWriter();
         out.write(result);
         out.flush();
         out.close();

   }
}
